import socket
import subprocess
import MySQLdb
import re
import datetime

host = ''
port = 54321	#Authen Server port

print "Authen Server Start at port", port

socketv4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketv4.bind((host,port))
socketv4.listen(20)

while True:
	conn, address = socketv4.accept()
	registime = datetime.datetime.now()
	print "Accept connection from %s at %s" %(address[0], registime)
	while True:
		data_in = conn.recv(1024)
		conn.close()
		
		if(data_in == ""):
			print "No data recieve\n\n"
			break;

		#check exit command use for emergency case
		elif(data_in == 'exit' or data_in == 'quit' or data_in == 'end'):
			print "End the program"
			quit()

		else:
			print "Recieving Data...\n" , data_in
		
			
			matchobj = re.search( r'(HWaddr|ether) ([0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2}:[0-9A-Fa-f]{2})', data_in, re.M|re.I)
			if matchobj is not None:
				print "MacAddress: ", matchobj.group(2)
				macaddress = "'" +  matchobj.group(2) + "'"
			else:
				macaddress = 'NULL'

			matchobj = re.search( r'(inet addr:|inet )([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})', data_in, re.M|re.I)
			if matchobj is not None:
				print "IPv4 Address: ", matchobj.group(2)
				ipv4address = "'" + matchobj.group(2) + "'"
			else:
				ipv4address = 'NULL'

			matchobj = re.search( r'(inet6 addr:|inet6) ([0-9A-F]{1,4}.*)(/.*|  prefixlen.*)(Global|global)', data_in, re.M|re.I)
			if matchobj is not None:
				print "IPv6 Address: ", matchobj.group(2)
				ipv6address = "'" + matchobj.group(2) + "'"
			else:
				ipv6address = 'NULL'
		
                #check exit command use for emergency case
                	if(data_in == 'exit' or data_in == 'quit' or data_in == 'end'):
                        	print "End the program"
                        	quit()
                

                #update mysql Agent's table
			if(macaddress == 'NULL'):
				print "Data format invalid"
				break;
			
			db = MySQLdb.connect('localhost', 'mysql', 'mysql', 'Agent_DB')
             		with db:
                        	cursor = db.cursor()
                        	cursor.execute ("UPDATE agent SET IPv4Address=%s, IPv6Address=%s, Registime='%s' WHERE MacAddress=%s " % (ipv4address, ipv6address, registime, macaddress))
				cursor.execute ("UPDATE server SET IPv4Address=%s, IPv6Address=%s, Registime='%s' WHERE MacAddress=%s "% (ipv4address, ipv6address, registime, macaddress))
				print "Update Agent list Successfully\n\n"
			cursor.close()
			break;
